package com.run.cat.common.security;

import com.run.cat.common.util.JWTUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;


@Slf4j
public class ShiroDbRealm extends AuthorizingRealm {


    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JWTToken;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken)  {
        String  token = (String) authcToken.getCredentials();
        String tokenName = JWTUtil.getUsername(token);
        String[] fields = tokenName.split(":");
        //手机号
        String password = fields[1];
        if (!JWTUtil.verify(token, tokenName, password)) {
           return null;
        }
        setAuthenticationCachingEnabled(true);
        // 认证缓存信息
        return new SimpleAuthenticationInfo(tokenName, token, getName());
    }

    /**
     * Shiro权限认证
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        SimpleAuthorizationInfo info = null;

        String userName=(String) principals.getPrimaryPrincipal();
        String[] fields = userName.split(":");
        Long userId=0L;
        if(fields.length >1){
             userId =Long.parseLong(fields[2]);
        }
   /*     List<UserPermissionVo> roleList = backResourceMapper.getRolePermissions(userId);
        Set<String> urlSet = new HashSet<String>();
        for (UserPermissionVo vo : roleList) {
            urlSet.add(vo.getResourceNo());
        }*/
        info = new SimpleAuthorizationInfo();
        //info.addStringPermissions(urlSet);
        return info;
    }

    /**
     * 检查redis中的token
     * @param token
     * @param redisToken
     * @return
     */
    private boolean checkRedisToken(String token,String redisToken){
        return StringUtils.isNotBlank(redisToken) && StringUtils.equals(token,redisToken);
    }






}
